package com.example.controller;

import com.example.common.AppResult;
import com.example.common.ResultCode;
import com.example.config.AppConfig;
import com.example.model.Article;
import com.example.model.Board;
import com.example.model.User;
import com.example.service.IArticleService;
import com.example.service.IBoardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: bjc
 * Date: 2025-10-11
 * Time: 09:31
 */
@Slf4j
@Tag(name = "帖子接口")
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IBoardService boardService;

    /**
     * 创建帖子
     * @param request 请求对象
     * @param boardId 板块id
     * @param title 帖子标题
     * @param content 帖子内容
     * @return 创建结果
     */
    @Operation(summary = "发布新帖")
    @PostMapping("/create")
    public AppResult createArticle(HttpServletRequest request,
                                   @Parameter(description = "板块Id") @RequestParam("boardId") @NonNull Long boardId,
                                   @Parameter(description = "帖子标题") @RequestParam("title") @NonNull String title,
                                   @Parameter(description = "帖子内容") @RequestParam("content") @NonNull String content) {
        //1.获取用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //2.判断用户状态
        if(user.getState() == 1){
            //表示用户被禁言，不能发帖
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //3.检验板块是否有效
        Board board = boardService.selectById(boardId);
        if(board == null || board.getDeleteState() == 1 || board.getState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            //抛出异常
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        //4.构建帖子对象
        Article article = new Article();
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        article.setTitle(title);
        article.setContent(content);
        //5.调用业务层创建帖子
        articleService.createArticle(article);
        //6.返回结果
        return AppResult.success();
    }

    /**
     * 根据板块id查询帖子列表,如果id为空，则显示所有帖子；如果id不为空，则显示指定板块的帖子
     * @param boardId 板块id
     * @return 帖子列表
     */
    @Operation(summary = "根据板块Id查询帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(
            @Parameter(description = "板块Id") @RequestParam(value = "boardId",required = false) Long boardId){
        //1.定义返回的集合对象
        List<Article> articleList = null;
        //2.根据板块id查询帖子列表
        if(boardId == null){
            //显示所有帖子
            articleList = articleService.selectAll();
            log.info("查询所有帖子列表");
        }else {
            //显示指定板块的帖子
            articleList = articleService.selectByBoardId(boardId);
            log.info("查询板块Id为{}的帖子列表",boardId);
        }
        //3.如果articleList为null，则返回空的json，需要创建一个空集合对象，不然的话，返回的json对象为null；
        // 如果创建了空集合对象，则返回的json对象为[]，而不是{}
        if(articleList == null){
            articleList = new ArrayList<>();
        }
        //4.返回结果
        return AppResult.success(articleList);
    }
    /**
     * 根据帖子id查询帖子详情
     * @param articleId 帖子id
     * @return 帖子详情
     */
    @Operation(summary = "根据帖子Id查询帖子详情")
    @GetMapping("/getDetailById")
    public AppResult<Article> getDetailById(HttpServletRequest request,
            @Parameter(description = "帖子id") @RequestParam("articleId") @NonNull Long articleId,
            @Parameter(description = "是否增加访问量") @RequestParam(value = "forEdit",defaultValue = "false") boolean forEdit){
        //forEdit 为true时，不增加访问量，表示用于编辑
        //获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //1.调用业务层查询帖子详情
        boolean increaseVisit = !forEdit;
        Article article = articleService.selectDetailById(articleId, increaseVisit);
        //2.判断结果是否为空
        if(article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断当前用户是否是帖子的作者
        if(user.getId() == article.getUserId()){
            article.setIsOwn(true);
        }
        //3.返回结果
        return AppResult.success(article);
    }
    /**
     * 修改帖子
     * @param request 请求对象，用来获取当前登录用户状态，用来判断用户是否被禁言，是否是作者
     * @param articleId 帖子id
     * @param title 帖子标题
     * @param content 帖子内容
     * @return 修改结果
     */
    @Operation(summary = "更新帖子")
    @PostMapping("/modify")
    public AppResult modifyArticle(HttpServletRequest request,
            @Parameter(description = "帖子id") @RequestParam("articleId") @NonNull Long articleId,
            @Parameter(description = "帖子标题") @RequestParam("title") @NonNull String title,
            @Parameter(description = "帖子内容") @RequestParam("content") @NonNull String content){
        //1.获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //2.判断用户状态
        if(user.getState() == 1){
            //表示用户被禁言，不能修改帖子
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //3.调用业务层代码获取帖子详情
        Article article = articleService.selectById(articleId);
        if(article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //4.判断当前用户是否是帖子的作者
        if(user.getId() != article.getUserId()){
            //打印日志
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //5.判断帖子状态是否正常
        if(article.getState() == 1 || article.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //6.调用业务层修改帖子
        articleService.modifyArticleById(articleId,title,content);
        return AppResult.success();
    }
    /**
     * 点赞
     * @param request 请求对象，用来获取当前登录用户状态
     * @param id 帖子id
     * @return 点赞结果
     */
    @Operation(summary = "点赞帖子")
    @PostMapping("/thumbsUp")
    public AppResult thumpsUp(HttpServletRequest request,
                              @Parameter(description = "帖子id") @RequestParam("id") @NonNull Long id){
        //1.获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //2.判断用户状态
        if(user.getState() == 1){
            //表示用户被禁言，不能点赞帖子
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //3.调用业务层点赞
        articleService.thumbsUpById(id);
        //省略检查帖子状态
        //4.返回结果
        return AppResult.success();
    }
    /**
     * 删除帖子
     * @param request 请求对象，用来获取当前登录用户状态
     * @param id 帖子id
     * @return 删除结果
     */
    @Operation(summary = "删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @Parameter(description = "帖子id") @RequestParam("id") @NonNull Long id){
        //1.获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //2.判断用户状态
        if(user.getState() == 1){
            //表示用户被禁言，不能删除帖子
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //3.获取帖子详情
        Article article = articleService.selectById(id);
        if(article == null || article.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //4.判断当前用户是否是帖子的作者
        if(user.getId() != article.getUserId()){
            //打印日志
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //5.调用业务层删除帖子
        articleService.deleteById(id);
        return AppResult.success();
    }
    @Operation(summary = "根据用户id查询帖子列表")
    @GetMapping("/getAllArticleByUserId")
    public AppResult<List<Article>>getAllArticleByUserId(HttpServletRequest request,
                @Parameter(description = "用户id") @RequestParam(value = "userId", required = false)Long userId){
        //1.判断用户id是否为空，如果为空，则从session中获取用户id
        if(userId == null){
            //从session中获取用户id
            HttpSession session = request.getSession(false);
            userId = ((User) session.getAttribute(AppConfig.USER_SESSION)).getId();
        }
        //2.调用业务层查询帖子列表
        List<Article> articleList = articleService.selectByUserId(userId);
        //3.返回结果
        return AppResult.success(articleList);
    }
}
